/* eslint-disable import/prefer-default-export */
/* eslint-disable class-methods-use-this */
/* eslint-disable no-unused-vars */
/* eslint-disable max-classes-per-file */
import Konva from 'konva'
import { ElMessageBox, ElInput } from 'element-plus'
import { h } from 'vue'
import { IKonvaTool } from '@/components/konvaUnits/tools/IKonvaTool'
import KonvaUtils from '@/components/konvaUnits/utils/konvaUtils'
import { useStore } from '@/store/index'

export class RulePen implements IKonvaTool {
  status: 'waiting' | 'drawing' = 'waiting'

  points: number[] = [0, 0, 0, 0]

  beginPos: number[] = [0, 0]

  endPos: number[] = [0, 0]

  angle: number = 0

  text: number[] = [0]

  konvaGroup: Konva.Group = new Konva.Group()

  mousedown(points: number[], scale: number, node: object): void {
    if (points === undefined) return
    this.konvaGroup.removeChildren()

    switch (this.status) {
      case 'waiting':
        this.status = 'drawing'
        this.beginPos = points
        break
      case 'drawing':
        this.status = 'waiting'
        this.endPos = points
        this.createLine(this.beginPos, this.endPos, scale)
        this.points = this.beginPos.concat(this.endPos)
        // this.setPlottingScaleValue(
        //   Math.round(KonvaUtils.getPositionLength(this.beginPos, this.endPos))
        // )
        // this.konvaGroup.removeChildren()
        break
      default:
        this.status = 'waiting'
    }
  }

  mousemove(points: number[], scale: number): void {
    if (points === undefined || this.status !== 'drawing') return
    this.konvaGroup.removeChildren()
    this.endPos = points
    this.createLine(this.beginPos, this.endPos, scale)
  }

  mouseup(points: number[], scale: number, node: object): void {}

  clean() {
    this.konvaGroup.removeChildren()
    this.points = [0, 0, 0, 0]
    this.beginPos = [0, 0]
    this.endPos = [0, 0]
    this.status = 'waiting'
  }

  click(e: any): void {
    throw new Error('Method not implemented.')
  }

  createLine(start: number[], end: number[], scale: number) {
    const lineLength = Math.round(KonvaUtils.getPositionLength(start, end))
    const fixLine = KonvaUtils.fixRadian(start, KonvaUtils.getAngle(start, end), lineLength)
    this.text = [KonvaUtils.getRealLength(lineLength, scale)]
    this.points = fixLine.points
    this.angle = fixLine.lineAngle

    const fence = new Konva.Line({
      points: this.points,
      stroke: 'red',
      lineCap: 'round'
    })

    this.konvaGroup.add(fence)
  }

  setPlottingScaleValue(length: number) {
    ElMessageBox.prompt('所画线表示的距离，单位（米）', '比例尺', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      center: true
    })
      .then((value: string, action: string) => {
        if (value === null || action !== 'confirm') return
        const store = useStore()
        store.globalParamAction.updatePlottingScale(Math.round(parseInt(value, 10) / length))
      })
      .catch(() => {})
  }
}
